from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker

from app.core.config import settings

# Create an asynchronous engine
engine = create_async_engine(settings.database_url, pool_pre_ping=True)

# Create a session factory
AsyncSessionLocal = sessionmaker(
    autocommit=False, 
    autoflush=False, 
    bind=engine, 
    class_=AsyncSession
)

async def get_db() -> AsyncSession:
    """
    Dependency function that yields a new SQLAlchemy async session.
    Ensures the session is always closed after the request.
    """
    async with AsyncSessionLocal() as session:
        try:
            yield session
        finally:
            await session.close()
